<?php
declare(strict_types=1);

namespace app\middleware;

use Closure;
use think\Request;
use think\Response;
use think\facade\Log;

class CrossDomain
{
    public function handle($request, Closure $next)
    {
        // 添加请求路径日志
        Log::debug('Request path: ' . $request->pathinfo());
        Log::debug('Request method: ' . $request->method());
        
        $origin = $request->header('Origin', '*');
        
        // 设置跨域头
        header('Access-Control-Allow-Origin: ' . $origin);
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With');
        header('Access-Control-Expose-Headers: Authorization');
        
        // 处理 OPTIONS 请求
        if ($request->method(true) == 'OPTIONS') {
            return response('', 204)
                ->header([
                    'Access-Control-Allow-Origin' => $origin,
                    'Access-Control-Allow-Credentials' => 'true',
                    'Access-Control-Allow-Methods' => 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
                    'Access-Control-Allow-Headers' => 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With',
                    'Access-Control-Expose-Headers' => 'Authorization',
                    'Access-Control-Max-Age' => '1728000'
                ]);
        }
        
        return $next($request);
    }
} 